package com.wanfu.configuration.shiro;

import com.wanfu.dao.*;
import com.wanfu.entity.*;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

public class MyShiroRealm extends AuthorizingRealm {

    @Resource
    private UserMapper userMapper;

    @Resource
    private UserToRoleMapper userToRoleMapper;

    @Resource
    private RoleToRightMapper roleToRightMapper;
    /**
     * 授权
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("权限配置-->MyShiroRealm.doGetAuthorizationInfo()");
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        User user = (User) principals.getPrimaryPrincipal();

        // 找到用户的所有角色
        List<UserToRole> userToRoleList =  userToRoleMapper.findRoleByUserId(user.getId());
        // 定义角色的集合
        List<Role> roleList = new ArrayList<>();
        for (UserToRole userToRole : userToRoleList) {
            // 装载角色
            roleList.add(userToRole.getRole());
            // shiro装载角色
            authorizationInfo.addRole(userToRole.getRole().getName());
            // 查询当前角色所有的权限
            List<RoleToRight> roleToRightList = roleToRightMapper.findRoleToRightByRoleId(userToRole.getRole().getId());
            List<Right> rightList = new ArrayList<>();
            for (RoleToRight roleToRight : roleToRightList) {
                // 装载当前角色的权限
                rightList.add(roleToRight.getRight());
                // shiro装载当前角色的权限
                authorizationInfo.addStringPermission(roleToRight.getRight().getName());
            }
            // 把当前角色所有的权限存入角色备用
            userToRole.getRole().setRightList(rightList);
        }
        // 把当前用户的所有角色（含权限）存入到用户备用
        user.setRoleList(roleList);
        /*for (Role role : user.getRoleList()) {
            authorizationInfo.addRole(role.getName());
            for (SysPermission p : role.getPermissions()) {
                authorizationInfo.addStringPermission(p.getPermission());
            }
        }*/
        return authorizationInfo;
    }

    /*主要是用来进行身份认证的，也就是说验证用户输入的账号和密码是否正确。*/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
            throws AuthenticationException {
//        System.out.println("MyShiroRealm.doGetAuthenticationInfo()");
        //获取用户的输入的账号.
        String username = (String) token.getPrincipal();
//        System.out.println(token.getCredentials());
        //通过username从数据库中查找 User对象，如果找到，没找到.
        //实际项目中，这里可以根据实际情况做缓存，如果不做，Shiro自己也是有时间间隔机制，2分钟内不会重复执行该方法
        User user = userMapper.findUserByUserName(username);
//        System.out.println("----->>userInfo="+userInfo);
        if (user == null) {
            user = userMapper.findUserByMobile(username);
            if (user == null) {
                throw new AccountException("用户名不正确");
            }
        }
        if (user.getStatus() == 1) { //账户冻结
            throw new LockedAccountException();
        }
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                user, //用户名
                user.getPassword(), //密码
                getName()  //realm name
        );//ByteSource.Util.bytes(user.getUserName() + "fengyi"),//salt=username+salt
        return authenticationInfo;
    }

}
